/**
* CreditEase.cn Inc.
* Copyright (c) 2006-2016 All Rights Reserved.
*/
package com.huixue.cn.ztej.utils;

import java.security.Principal;
import java.util.List;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;

import com.huixue.cn.ztej.bean.Menu;
import com.huixue.cn.ztej.bean.Role;
import com.huixue.cn.ztej.bean.User;
import com.huixue.cn.ztej.dao.MenuDAO;
import com.huixue.cn.ztej.dao.RoleMapper;
import com.huixue.cn.ztej.dao.UserMapper;


/** 
* @author huhongxing 
* @E-mail hongxinghu@creditease.cn
* @version v1.0 创建时间：2016年3月30日 上午11:06:23 
* 用户工具类
*/
public class UserUtils {

	private static UserMapper userDao = SpringContextHolder.getBean(UserMapper.class);
	private static RoleMapper roleDao = SpringContextHolder.getBean(RoleMapper.class);
	private static MenuDAO menuDao = SpringContextHolder.getBean(MenuDAO.class);
	
	public static final String USER_CACHE = "userCache";
	public static final String SESSIONID_CACHE = "sessionforCache";
	public static final String OPPENID_CACHE = "openforCache";
	public static final String USER_CACHE_ID_ = "id_";

	public static final String CACHE_ROLE_LIST = "roleList";
	public static final String CACHE_MENU_LIST = "menuList";
	
	
	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public static User get(int id){
		User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
		if (user ==  null){
			user = userDao.findById(id);
			if (user == null){
				return null;
			}
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getUser_id(), user);
		}
		return user;
	}
	
	/**
	 * 更新user
	 * @param id
	 */
	public static void replace(int id){
		CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + id);
		User user = userDao.findById(id);
		CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getUser_id(), user);
	}
	
	
	
	/**
	 * 根据sessionID获取用户
	 * @param SessionID
	 * @return 取不到返回null
	 */
	public static User getbySessionID(String SessionID){
		Object o = CacheUtils.get(SESSIONID_CACHE, SessionID);
		if(o!=null){
			int id = (Integer)o;
			return get(id);
		}
		return null;
	}
	
	/**
	 * 保存SessionId
	 * @param id
	 */
	public static void putSessionID(String SessionID,int id){
		CacheUtils.put(SESSIONID_CACHE, SessionID,id);
	}
	
	/**
	 * 更新sessionID
	 * @param SessionID
	 * @return 取不到返回null
	 */
	public static void replaceSessionID(String SessionID,int id){
		CacheUtils.remove(SESSIONID_CACHE, SessionID);
		CacheUtils.put(SESSIONID_CACHE, SessionID,id);
		
	}
	
	/**
	 * 根据openID获取用户
	 * @param SessionID
	 * @return 取不到返回null
	 */
	public static User getbyOpenID(String openID){
		User user = null;
		Object o = CacheUtils.get(OPPENID_CACHE, openID);
		if(o!=null){
			int id = (Integer)o;
			user = get(id);
			if(user == null){
				user = userDao.findByOpenId(openID);
				CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getUser_id(), user);
			}
		}else{
			user = userDao.findByOpenId(openID);
			get(user.getUser_id());
			CacheUtils.put(OPPENID_CACHE,openID,user.getUser_id());
		}
		return user;
	}
	
	/**
	 * 更新sessionID
	 * @param SessionID
	 * @return 取不到返回null
	 */
	public static void replaceOpenID(String openID,int id){
		CacheUtils.remove(OPPENID_CACHE, openID);
		CacheUtils.put(OPPENID_CACHE, openID,id);
		
	}
	
	/**
	 * 根据openID获取用户
	 * @param SessionID
	 * @return 取不到返回null
	 */
	public static void putOpenID(String openID,int userId){
		if(CacheUtils.get(OPPENID_CACHE, openID)!=null){
			if(userId != (Integer)CacheUtils.get(OPPENID_CACHE, openID)){
				CacheUtils.put(OPPENID_CACHE, openID,userId);
			}
		}else{
			CacheUtils.put(OPPENID_CACHE, openID,userId);
		}
		
	}
	
	
	
	
	
	/**
	 * 清除当前用户缓存
	 */
	public static void clearCache(){
		removeCache(CACHE_ROLE_LIST);
		removeCache(CACHE_MENU_LIST);
		UserUtils.clearCache(getUser());
	}
	
	/**
	 * 清除指定用户缓存
	 * @param user
	 */
	public static void clearCache(User user){
	    CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getUser_id());
	}
	
	/**
	 * 获取当前用户
	 * @return 取不到返回 new User()
	 */
	public static User getUser(){
		HttpServletRequest request;
//		String sessionId = request.getSession().getId();
//		if (sessionId!=null){
//			User user = null;
//			if (user != null){
//				return user;
//			}
//			return new User();
//		}
		// 如果没有登录，则返回实例化空的User对象。
		return new User();
	}

	/**
	 * 获取当前用户角色列表
	 * @return
	 */
	public static List<Role> getRoleList(){
		@SuppressWarnings("unchecked")
		List<Role> roleList = (List<Role>)getCache(CACHE_ROLE_LIST);
		if (roleList == null){
			User user = getUser();
			roleList = roleDao.listRole(-1);
			putCache(CACHE_ROLE_LIST, roleList);
		}
		return roleList;
	}
	
	/**
	 * 获得当前用户授权菜单树
	 * @return
	 */
//	public static List<TreeNode<Menu>> getMenuTree(){
//		 List<Menu> menuList = UserUtils.getMenuList();
//	     List<TreeNode<Menu>>  menuTree = TreeUtils.createMenuTree(menuList);
//	     return menuTree;
//	}
	
	/**
	 * 获取当前用户授权菜单
	 * @return
	 */
	public static List<Menu> getMenuList(){
		@SuppressWarnings("unchecked")
		List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_LIST);
		if (menuList == null || menuList.size()==0){
			User user = getUser();
			
            putCache(CACHE_MENU_LIST, menuList);
		}
		return menuList;
	}
	
	/**
     * 获取当前用户授权菜单 ---控制右侧菜单权限，
     * 如果使用同一个方法 当用户没有菜单权限时，左侧的导航菜单也会不展示，故做区别处理
     * @return
     */
    public static List<Menu> getList(){
        @SuppressWarnings("unchecked")
        List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_LIST);
        if (menuList == null){
            User user = getUser();
            
            putCache(CACHE_MENU_LIST, menuList);
        }
        return menuList;
    }
    
	/**
	 * 获取授权主要对象
	 */
//	public static Subject getSubject(){
//		return SecurityUtils.getSubject();
//	}
//	
//	/**
//	 * 获取当前登录者对象
//	 */
//	public static Principal getPrincipal(){
//		try{
//			Subject subject = SecurityUtils.getSubject();
//			Principal principal = (Principal)subject.getPrincipal();
//			if (principal != null){
//				return principal;
//			}
////			subject.logout();
//		}catch (Exception e){
//			
//		}
//		return null;
//	}
//	
//	public static Session getSession(){
//		try{
//			Subject subject = SecurityUtils.getSubject();
//			Session session = subject.getSession(false);
//			if (session == null){
//				session = subject.getSession();
//			}
//			if (session != null){
//				return session;
//			}
////			subject.logout();
//		}catch (Exception e){
//			
//		}
//		return null;
//	}
	
	// ============== User Cache ==============
	
	public static Object getCache(String key) {
		return getCache(key, null);
	}
	
	public static Object getCache(String key, Object defaultValue) {
//		Object obj = getSession().getAttribute(key);
		Object obj = null;
		return obj==null?defaultValue:obj;
	}

	public static void putCache(String key, Object value) {
//		getCacheMap().put(key, value);
//		getSession().setAttribute(key, value);
	}

	public static void removeCache(String key) {
//		getCacheMap().remove(key);
//		getSession().removeAttribute(key);
	}
	
    
    public static List<Menu> getSysMenuList(){
        @SuppressWarnings("unchecked")
        List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_LIST);
        if (menuList == null){
           
//            putCache(CACHE_MENU_LIST, menuList);
        }
        return menuList;
    }
 
    /**
     * 根据登录媒介获取用户信息
     * @param openId 微信openId
     * @return 用户信息
     */
	public static User getByOpenId(String openId) {
		if(Strings.isEmpty(openId)) {
			return null;
		}
		return userDao.findByOpenId(openId);
	}
	
	
	
}
